package com.audaque.springboot.foshanupload.security.util;

import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.security.model.MyGrantedAuthority;
import com.audaque.springboot.foshanupload.security.model.MyUserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zgb
 * @desc 处理session部分
 * @date 2023-07-13 16:52:37
 */
@Slf4j
public class SecurityContextAuthentication2TransmittableThreadLocalCurrentUserUtil {


    public static void covert(String id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof AnonymousAuthenticationToken){
            log.debug("匿名访问:AnonymousAuthenticationToken：针对匿名用户的Token");
            return;
        }
        if(authentication==null){
            return;
        }
        String username = authentication.getName();
        log.debug("username:" + username);
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        log.debug("authorities:" + authorities);
        Object credentials = authentication.getCredentials();
        log.debug("credentials:" + credentials);
        MyUserDetail details = (MyUserDetail) authentication.getDetails();
        Object principal = authentication.getPrincipal();

        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = BeanUtil.toBean(details, TransmittableThreadLocalCurrentUser.class);
        transmittableThreadLocalCurrentUser.setSessionId(id);

        Set<MyGrantedAuthority> authorities1 = details.getAuthorities();
        Set<String> collect = authorities1.stream().map(e -> e.getAuthority()).collect(Collectors.toSet());
        transmittableThreadLocalCurrentUser.setRoleIds(collect);
        //父子线程传递上下文（用户信息）,  TransmittableThreadLocal，避免重复解析用户
        TransmittableThreadLocalCurrentUser.setCurrentUser(transmittableThreadLocalCurrentUser);

    }


}
